<template>
  <q-field v-model="editor" :readonly="readonly" class="qx-editor" no-error-icon v-bind="$attrs" @focus="fieldFocus">
    <template v-slot:control>
      <q-editor ref="QxEditor" v-model="editor" v-bind="editorBind" @update:model-value="change" />
    </template>
  </q-field>
</template>

<script setup>
import { computed, nextTick, ref, toRef, watch } from 'vue'

const props = defineProps({
  input: Function,
  readonly: Boolean,
  clearable: Boolean,
  placeholder: String,
  modelValue: [String, Number]
})

const emits = defineEmits(['input', 'update:modelValue'])

const QxEditor = ref(null)

const editorBind = computed(() => {
  return {
    'toolbar-rounded': true, 'min-height': '5rem', placeholder: props.placeholder, readonly: props.readonly
  }
})

const editor = ref('')

const initData = () => {
  if (editor.value === props.modelValue) return
  editor.value = props.modelValue || ''
}

watch(toRef(props, 'modelValue'), () => initData(), { immediate: true })

const fieldFocus = () => nextTick(() => QxEditor.value.focus())

const change = e => {
  emits('update:modelValue', e)

  if (props.input) props.input(e)
  else emits('input', e)
}

</script>